package com.css.fxfzdzzh.modules.reportManagement.service;

import cn.hutool.core.convert.Convert;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.enums.DisasterTypeEnum;
import com.css.fxfzdzzh.enums.ModelEnum;
import com.css.fxfzdzzh.enums.SandLiqueFactionEnum;
import com.css.fxfzdzzh.modules.eqLandslide.count.entity.DzzhTaskModel;
import com.css.fxfzdzzh.modules.eqLandslide.count.repository.EqLandslideRepository;
import com.css.fxfzdzzh.modules.evaluate.entity.TaskVersion;
import com.css.fxfzdzzh.modules.evaluate.repository.SoftSoilRepository;
import com.css.fxfzdzzh.modules.mapManagement.repository.MapRepository;
import com.css.fxfzdzzh.modules.mapManagement.vo.MapAttachment;
import com.css.fxfzdzzh.modules.reportManagement.entity.BreakReport;
import com.css.fxfzdzzh.modules.reportManagement.entity.HistoryReport;
import com.css.fxfzdzzh.modules.reportManagement.entity.MultipleReport;
import com.css.fxfzdzzh.modules.reportManagement.entity.ReportBack;
import com.css.fxfzdzzh.modules.reportManagement.param.MultiplePageQueryParam;
import com.css.fxfzdzzh.modules.reportManagement.param.PageQueryParam;
import com.css.fxfzdzzh.modules.reportManagement.repository.MultipleReportRepository;
import com.css.fxfzdzzh.modules.reportManagement.repository.ReportRepository;
import com.css.fxfzdzzh.modules.sandLiquefaction.entity.AhpMathWeight;
import com.css.fxfzdzzh.modules.sandLiquefaction.entity.DzzhModelSandLiquefaction;
import com.css.fxfzdzzh.modules.sandLiquefaction.repository.SandLiquefactionRepository;
import com.css.fxfzdzzh.modules.surfaceRupture.entity.SurfaceRupture;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskEntity;
import com.css.fxfzdzzh.modules.taskManage.repository.TaskRepository;
import com.css.fxfzdzzh.util.*;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年05月10日  18:12
 */
@Service
public class MultipleReportService {

    @Resource
    MultipleReportRepository multipleReportRepository;

    @Value("${file.localDir}")
    private String localDir;

    @Resource
    TaskRepository taskRepository;

    @Resource
    SUserService sUserService;

    @Resource
    ReportRepository reportRepository;

    @Resource
    EqLandslideRepository eqLandslideRepository;

    @Resource
    SandLiquefactionRepository sandLiquefactionRepository;

    @Resource
    SoftSoilRepository softSoilRepository;

    @Resource
    MapRepository mapRepository;

    public Map<String, Object> multiplePage(MultiplePageQueryParam param, int curPage, int pageSize) {
        return multipleReportRepository.multiplePage(param, curPage, pageSize);
    }

    public MultipleReport getReport(String reportId) {
        return multipleReportRepository.getReportById(reportId);
    }

    public void downloadReport(String reportId, String type, HttpServletResponse res) {
        MultipleReport report = multipleReportRepository.getReportById(reportId);
        String filePath = report.getReportSavePath();
        String fileName = "";
        //def 1系统默认 2、用户自己的
        if ("1".equals(type)) {
            //系统生成的报告
            fileName = report.getDiskSystemCreateMultipleReportName();
        } else if ("2".equals(type)){
            //用户上传的报告
            fileName = report.getDiskUploadMultipleReportName();
        } else if ("3".equals(type)){
            //审核不通过退回的附件
            fileName = report.getRejectFile();
        }
        FileUploadUtil.download(filePath + File.separator + fileName, res);
    }

    public RestResponse uploadReport(MultipartFile file, String num) throws IOException {
        if (file == null) {
            return ResponseCreator.createFailResponse("上传失败，请选择文件");
        }
        TaskEntity taskEntity = taskRepository.getTaskByNum(num);
        String reportId = taskEntity.getReportId();
        //获取文件名称
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String filePrefix = fileName.split("\\.")[0];
        String fileType = fileName.split("\\.")[1];
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowStr = sdf.format(now);
        String localReportName = filePrefix + nowStr + "." + fileType;
        //获取文件上传的本地路径
        String savePath = localDir;
        //上传文件
        uploadFile(localReportName, savePath, file);
        if(StringUtils.isBlank(reportId)){
            //表示还未生成过报告信息
            MultipleReport report = new MultipleReport();
            reportId = UUIDGenerator.getUUID();
            report.setDtmrId(reportId);
            report.setUploadMultipleReportName(fileName);
            report.setDiskUploadMultipleReportName(localReportName);
            report.setUploadMultipleReportTime(new Date());
            report.setUploadMultipleUserId(PlatformSessionContext.getUserID());
            report.setReportSavePath(savePath);
            report.setCheckStatus("0");
            report.setNum(taskEntity.getTaskNum());
            report.setDistrict(taskEntity.getTaskDistrict());
            report.setTaskName(taskEntity.getTaskName());
            multipleReportRepository.save(report);
            //关联地表劈裂带
            taskRepository.updateReportId(taskEntity.getDtId(),reportId);
        }else{
            //已经存在报告信息
            MultipleReport report = multipleReportRepository.getReportById(reportId);
            report.setUploadMultipleReportName(fileName);
            report.setDiskUploadMultipleReportName(localReportName);
            report.setUploadMultipleReportTime(new Date());
            report.setUploadMultipleUserId(PlatformSessionContext.getUserID());
            multipleReportRepository.updateUploadReport(report);
        }
        //保存历史上传报告
        saveHistoryReport(fileName,localReportName,localDir,taskEntity.getTaskNum());
        return ResponseCreator.createSuccessResponse(multipleReportRepository.getReportById(reportId));
    }

    private void saveHistoryReport(String fileName, String localReportName, String localDir, String taskNum) {
        HistoryReport historyReport = new HistoryReport();
        historyReport.setDthrId(UUIDGenerator.getUUID());
        historyReport.setReportName(fileName);
        historyReport.setDiskReportName(localReportName);
        historyReport.setFileSavePath(localDir);
        String userID = PlatformSessionContext.getUserID();
        historyReport.setUploadUserId(userID);
        String userJson = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        historyReport.setUploadUserName(sUser.getUserName());
        historyReport.setUploadTime(new Date());
        historyReport.setReportType("2");
        historyReport.setNum(taskNum);
        reportRepository.saveHistoryReport(historyReport);
    }

    private void uploadFile(String fileName, String savePath, MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        //判断文件夹是否存在如果不存在则创建
        if (!new File(savePath).exists()) {
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, fileName);
        multipartFile.transferTo(file);
    }

    public void submitCheak(String reportId) {
        String userID = PlatformSessionContext.getUserID();
        String userJson = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        MultipleReport reportById = multipleReportRepository.getReportById(reportId);
        if(StringUtils.isBlank(reportById.getUploadMultipleReportName())){
            throw new RuntimeException("提交审核失败,上传最终版本报告后才可提交审核");
        }
        multipleReportRepository.submitCheak(reportId,userID,sUser.getUserName());
    }

    public MultipleReport createMultipleReport(String taskNum) throws Exception{
        TaskEntity taskEntity = taskRepository.getTaskByNum(taskNum);
        Map<String, Object> paramMap = buildReportData(taskEntity);
        List<MapAttachment> mapAttachmentList = mapRepository.getMapAttachmentByCategory(Arrays.asList("6","7"));
        buildImage(mapAttachmentList,paramMap);
        Map<String, String> map = createReport(paramMap);
        if(PlatformObjectUtils.isNotEmpty(taskEntity)){
            String reportId = "";
            if(StringUtils.isBlank(taskEntity.getReportId())){
                System.out.println("开始组建数据了1");
                MultipleReport report = new MultipleReport();
                reportId = UUIDGenerator.getUUID();
                //表示之前未生成过报告信息
                report = new MultipleReport();
                report.setDtmrId(reportId);
                report.setReportSavePath(map.get("rootPath"));
                report.setCheckStatus("0");
                setData(report,map,taskEntity);
                //save
                multipleReportRepository.save(report);
                taskRepository.updateReportId(taskEntity.getDtId(),reportId);
            }else{
                System.out.println("开始组建数据了2");
                //查询报告信息
                MultipleReport report = multipleReportRepository.getReportById(taskEntity.getReportId());
                reportId = report.getDtmrId();
                setData(report,map,taskEntity);
                //update
                multipleReportRepository.updateSystemCreateReport(report);
            }
            System.out.println("组建数据完成");
            return multipleReportRepository.getReportById(reportId);
        }
        System.out.println("没有任何返回数据");
        return new MultipleReport();
    }

    private void buildImage(List<MapAttachment> mapAttachmentList, Map<String, Object> paramMap) {
        if(PlatformObjectUtils.isNotEmpty(mapAttachmentList)&& mapAttachmentList.size()>0){
            Map<String, List<MapAttachment>> collect = mapAttachmentList.stream().collect(Collectors.groupingBy(MapAttachment::getMapLevel2Category));
            //地形地貌图
            Optional.ofNullable(collect.get("8")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("landFormImage",list);
                }
            });
            //地层岩性分布图
            Optional.ofNullable(collect.get("9")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("litholigyImage",list);
                }
            });
            //活断层分布图
            Optional.ofNullable(collect.get("10")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("activeImage",list);
                }
            });
            //地震滑坡评估结果
            Optional.ofNullable(collect.get("11")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400,entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("landslideImage",list);
                }
            });
            Optional.ofNullable(collect.get("12")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("landslideImage",list);
                }
            });
            Optional.ofNullable(collect.get("13")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("landslideImage",list);
                }
            });
            //砂土液化评估结果
            Optional.ofNullable(collect.get("14")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("liquefyImage",list);
                }
            });
            Optional.ofNullable(collect.get("15")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400,entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("liquefyImage",list);
                }
            });
            Optional.ofNullable(collect.get("16")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("liquefyImage",list);
                }
            });

            //砂土液化评估结果
            Optional.ofNullable(collect.get("17")).ifPresent(x->{
                if(PlatformObjectUtils.isNotEmpty(x)){
                    List<Map<String,PictureRenderData>> list = new ArrayList<>();
                    x.forEach(entity->{
                        Map<String,PictureRenderData> map = new HashMap<>();
                        map.put("picture",new PictureRenderData(250, 400, entity.getAttachFullPath()));
                        list.add(map);
                    });
                    paramMap.put("softImage",list);
                }
            });
        }
    }

    private Map<String, Object> buildReportData(TaskEntity taskEntity) throws Exception{
        Map<String, Object> paramMap = new HashMap<>();
        Calendar calendar =Calendar.getInstance();
        calendar.setTime(new Date());
        //年
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        // 获取当前月
        String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        String createTime = com.css.fxfzdzzh.util.StringUtils.transLowNumToUpper(year)+"年"+com.css.fxfzdzzh.util.StringUtils.transLowNumToUpper(month)+"月";
        //设置创建报告时间
        paramMap.put("createTime",createTime);
        String disasterType = taskEntity.getDisasterType();
        Boolean hasLandslide = true;
        Boolean hasLiquefaction = true;
        Boolean hasSubsidence = true;
        String  landslide ="地震滑坡";
        String  liquefy ="砂土液化";
        String  softsolid ="软土震陷";
        List<Map<String,Object>> referenceList = new ArrayList<>(1);
        if(StringUtils.isNotBlank(disasterType)){
            String  landslideName1 = "指数模型和逻辑斯蒂模型";
            String  landslideName2 = "黄土高原模型";
            String  landslideName3 = "层次分析法模型";
            String[] split = disasterType.split(",");
            if(Arrays.asList(split).contains(DisasterTypeEnum.LANDSLIDE.getState()+"")){
                landslide +="(任务关联)";
                DzzhTaskModel dzzhTaskModel = eqLandslideRepository.getDzzhTaskModelByTaskIdAndResultStatus(taskEntity.getDtId(), "2");
                if(PlatformObjectUtils.isEmpty(dzzhTaskModel)){
                    hasLandslide = false;
                }else{
                    //包含地震滑坡
                    switch (dzzhTaskModel.getModelType()) {
                        case "1"://层次分析法模型
                            landslideName3 +="(任务关联模型):";
                            landslideName1 +="(非任务关联模型可删除)";
                            landslideName2 +="(非任务关联模型可删除)";
                            break;
                        case "2"://黄土高原模型
                            landslideName2 +="(任务关联模型):";
                            landslideName1 +="(非任务关联模型可删除)";
                            landslideName3 +="(非任务关联模型可删除)";
                            break;
                        case "3"://地层岩性
                        case "4"://道路
                            landslideName1 +="(任务关联模型):";
                            landslideName3 +="(非任务关联模型可删除)";
                            landslideName2 +="(非任务关联模型可删除)";
                            break;
                        default:
                            landslideName3+="(非任务关联模型可删除):";
                            landslideName2+="(非任务关联模型可删除):";
                            landslideName1+="(非任务关联模型可删除):";
                    }
                }
            }else{
                landslide +="(任务未关联可删除)";
                landslideName1 = "指数模型和逻辑斯蒂模型(非任务关联模型可删除)";
                landslideName2 = "黄土高原模型(非任务关联模型可删除)";
                landslideName3 = "层次分析法模型(非任务关联模型可删除)";
            }
            paramMap.put("landslideName1",landslideName1);
            paramMap.put("landslideName2",landslideName2);
            paramMap.put("landslideName3",landslideName3);
            String liquefyName="";
            String ahpName="";
            String isDelete = "液化等级与液化指数的对应关系";
            String referenceName = "液化判别标准贯入锤击数基准";
            //砂土液化
            if(Arrays.asList(split).contains(DisasterTypeEnum.LIQUEFACTION.getState()+"")){
                liquefy +="(任务关联)";
                DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskEntity.getDtId(), "2");
                if(PlatformObjectUtils.isEmpty(modelSandLiquefaction)){
                    hasLiquefaction = false;
                }else{
                    String algorithmType = modelSandLiquefaction.getAlgorithmType();
                    Map<String,Object> map = new LinkedHashMap<>();
                    if(String.valueOf(SandLiqueFactionEnum.SPT.getState()).equals(algorithmType)){
                        //包含砂土液化
                        switch (modelSandLiquefaction.getOperands()) {
                            case "1"://饱和砂土或粉土
                                liquefyName = "标贯法饱和砂土或粉土(任务关联模型)：";
                                isDelete += "（可删除）";
                                map = getReferenceMap("1");
                                break;
                            case "2"://饱和黄土
                                liquefyName = "标贯法饱和黄土(任务关联模型)：";
                                isDelete += "（可删除）";
                                map = getReferenceMap("2");
                                break;
                            default:
                                liquefyName = "";
                        }
                    }
                    if(String.valueOf(SandLiqueFactionEnum.INDEX.getState()).equals(algorithmType)){
                        //包含砂土液化
                        switch (modelSandLiquefaction.getOperands()) {
                            case "1"://饱和砂土或粉土
                                liquefyName = "液化指数法饱和砂土或粉土(任务关联模型)：";
                                map = getReferenceMap("3");
                                break;
                            case "2"://饱和黄土
                                liquefyName = "液化指数法饱和黄土(任务关联模型)：";
                                map = getReferenceMap("4");
                                break;
                            default:
                                liquefyName = "";
                        }
                    }
                    if(String.valueOf(SandLiqueFactionEnum.AHP.getState()).equals(algorithmType)){
                        ahpName = "层次分析法(任务关联模型)";
                        referenceName+="(非任务关联可删除)";
                        isDelete += "（可删除）";
                        Integer selectedMatrix = modelSandLiquefaction.getSelectedMatrix();
                        if(1==selectedMatrix){
                            //默认权重
                            getDefaultWeight(paramMap);
                        }else if(2==selectedMatrix){
                            //计算得到的权重
                            AhpMathWeight ahpMathWeight = sandLiquefactionRepository.getAhpMathWeight(modelSandLiquefaction.getDmslId(),taskEntity.getDtId());
                            getMathWeight(ahpMathWeight,paramMap);
                        }
                    }else{
                        ahpName = "层次分析法(非任务关联模型可删除)";
                    }
                    referenceList.add(map);
                }
            }else{
                liquefy +="(任务未关联可删除)";
            }
            paramMap.put("referenceName",referenceName);
            paramMap.put("liquefyName",liquefyName);
            paramMap.put("ahpName",ahpName);
            paramMap.put("isDelete",isDelete);
            if(Arrays.asList(split).contains(DisasterTypeEnum.SUBSIDENCE.getState()+"")){
                TaskVersion softSoil = softSoilRepository.findDataByTaskId(taskEntity.getDtId(), "2");
                if(PlatformObjectUtils.isEmpty(softSoil)){
                    hasSubsidence = false;
                }
                softsolid+="(任务关联)";
            }else{
                softsolid +="(任务未关联可删除)";
            }
        }
        paramMap.put("softsolid",softsolid);
        paramMap.put("landslide",landslide);
        paramMap.put("liquefy",liquefy);
        paramMap.put("referenceList",referenceList);
        if(!hasSubsidence && !hasLandslide && !hasLiquefaction){
            throw new RuntimeException("报告生成失败,"+taskEntity.getTaskNum()+"没有选择任何模型进行数据评估");
        }
        return paramMap;
    }

    private void getMathWeight(AhpMathWeight ahpMathWeight, Map<String, Object> paramMap) {
        paramMap.put("weight1",ahpMathWeight.getSolumFactorWeight());
        paramMap.put("weight2",ahpMathWeight.getLandformFactorWeight());
        paramMap.put("weight3",ahpMathWeight.getPgaFactorWeight());
        paramMap.put("weight4",ahpMathWeight.getRiverFactorWeight());
        paramMap.put("weight5",ahpMathWeight.getPlaceFactorWeight());
        paramMap.put("ratio1",ahpMathWeight.getSolumCategoryWeight1());
        paramMap.put("ratio2",ahpMathWeight.getSolumCategoryWeight2());
        paramMap.put("ratio3",ahpMathWeight.getSolumCategoryWeight3());
        paramMap.put("ratio4",ahpMathWeight.getSolumCategoryWeight4());
        paramMap.put("ratio5",ahpMathWeight.getLandformCategoryWeight1());
        paramMap.put("ratio6",ahpMathWeight.getLandformCategoryWeight2());
        paramMap.put("ratio7",ahpMathWeight.getLandformCategoryWeight3());
        paramMap.put("ratio8",ahpMathWeight.getLandformCategoryWeight4());
        paramMap.put("ratio9",ahpMathWeight.getLandformCategoryWeight5());
        paramMap.put("ratio10",ahpMathWeight.getPgaCategoryWeight1());
        paramMap.put("ratio11",ahpMathWeight.getPgaCategoryWeight2());
        paramMap.put("ratio12",ahpMathWeight.getRiverCategoryWeight1());
        paramMap.put("ratio13",ahpMathWeight.getRiverCategoryWeight2());
        paramMap.put("ratio14",ahpMathWeight.getRiverCategoryWeight3());
        paramMap.put("ratio15",ahpMathWeight.getRiverCategoryWeight4());
        paramMap.put("ratio16",ahpMathWeight.getRiverCategoryWeight5());
        paramMap.put("ratio17",BigDecimal.ZERO);
        paramMap.put("ratio18",ahpMathWeight.getPlaceCategoryWeight1());
        paramMap.put("ratio19",ahpMathWeight.getPlaceCategoryWeight2());
        paramMap.put("ratio20",ahpMathWeight.getPlaceCategoryWeight3());
    }

    private void getDefaultWeight(Map<String, Object> paramMap) {
        paramMap.put("weight1",BigDecimal.valueOf(0.434));
        paramMap.put("weight2",BigDecimal.valueOf(0.271));
        paramMap.put("weight3",BigDecimal.valueOf(0.172));
        paramMap.put("weight4",BigDecimal.valueOf(0.076));
        paramMap.put("weight5",BigDecimal.valueOf(0.047));
        paramMap.put("ratio10",BigDecimal.valueOf(0.333));
        paramMap.put("ratio11",BigDecimal.valueOf(0.667));
        paramMap.put("ratio12",BigDecimal.valueOf(0.472));
        paramMap.put("ratio13",BigDecimal.valueOf(0.292));
        paramMap.put("ratio14",BigDecimal.valueOf(0.122));
        paramMap.put("ratio15",BigDecimal.valueOf(0.075));
        paramMap.put("ratio16",BigDecimal.valueOf(0.039));
        paramMap.put("ratio18",BigDecimal.valueOf(0.751));
        paramMap.put("ratio19",BigDecimal.valueOf(0.178));
        paramMap.put("ratio20",BigDecimal.valueOf(0.070));
        paramMap.put("ratio17",BigDecimal.ZERO);
        paramMap.put("ratio5",BigDecimal.valueOf(0.044));
        paramMap.put("ratio6",BigDecimal.valueOf(0.075));
        paramMap.put("ratio7",BigDecimal.valueOf(0.143));
        paramMap.put("ratio8",BigDecimal.valueOf(0.268));
        paramMap.put("ratio9",BigDecimal.valueOf(0.471));
        paramMap.put("ratio1",BigDecimal.valueOf(0.560));
        paramMap.put("ratio2",BigDecimal.valueOf(0.272));
        paramMap.put("ratio3",BigDecimal.valueOf(0.131));
        paramMap.put("ratio4",BigDecimal.valueOf(0.037));
    }
    //液化判别标准贯入锤击数基准
    private Map<String, Object> getReferenceMap(String type) {
        Map<String, Object> map = new LinkedHashMap<>();
        if("1".equals(type) || "3".equals(type)){
            //标贯法饱和砂土或粉土
            map.put("refratio1","液化判别标准贯入锤击数基准值");
            map.put("refratio2","7");
            map.put("refratio3","10");
            map.put("refratio4","12");
            map.put("refratio5","16");
            map.put("refratio6","19");
        }else if("2".equals(type) || "4".equals(type)){
            //标贯法饱和砂土或粉土
            map.put("refratio1","液化判别标准贯入锤击数基准值");
            map.put("refratio2","7");
            map.put("refratio3","8");
            map.put("refratio4","9");
            map.put("refratio5","11");
            map.put("refratio6","13");
        }
        return map;
    }


    private Map<String, String> createReport(Map<String, Object> paramMap) throws Exception{
        // 文件存放根目录
        String rootPath = localDir;
        File dir = new File(rootPath);
        // 文件夹不存在则创建
        if (!dir.exists()) {
            boolean mkdir = dir.mkdir();
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowStr = sdf.format(now);
        String desFileName = "地震地质灾害危险性评估报告" +nowStr+ ".docx";
        String docxPath =  rootPath +File.separator+ desFileName;
        File file =  ResourceUtils.getFile("classpath:template/地质灾害危险性评估.docx");
        System.out.println("模板路径:--"+file.getAbsolutePath());
        if(!file.exists()){
            throw new RuntimeException("报告生成失败，获取不到模板信息！");
        }
        InputStream inputStream = new FileInputStream(file);

        //渲染表格  动态行
        try{
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder().bind("areaTownStructureList", policy)
                    .bind("referenceList",policy).build();
            XWPFTemplate template = XWPFTemplate.compile(inputStream,config).render(paramMap);
            OutputStream outDocx = Files.newOutputStream(Paths.get(docxPath));
            NiceXWPFDocument xwpfDocument = template.getXWPFDocument();
            // 输出word
            template.getXWPFDocument().write(outDocx);
            outDocx.flush();
            outDocx.close();
            inputStream.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        System.out.println("模板数据生成完成");
        Map<String, String> map = new HashMap<>(4);
        map.put("rootPath", rootPath);
        map.put("docxName", desFileName);
        return map;
    }

    private void setData(MultipleReport report, Map<String, String> map, TaskEntity taskEntity) {
        report.setSystemCreateMultipleReportName("地震地质灾害危险性评估报告.docx");
        report.setDiskSystemCreateMultipleReportName(map.get("docxName"));
        report.setSystemMultipleCreateUserId(PlatformSessionContext.getUserID());
        report.setSystemMultipleCreateTime(new Date());
        report.setNum(taskEntity.getTaskNum());
        report.setDistrict(taskEntity.getTaskDistrict());
        report.setCreateUserName(taskEntity.getCreateUserName());
        report.setTaskName(taskEntity.getTaskName());
    }

    public ReportBack getBackReport(String reportId) {
        MultipleReport report = multipleReportRepository.getReportById(reportId);
        if(PlatformObjectUtils.isNotEmpty(report) && "2".equals(report.getCheckStatus())){
            ReportBack reportBack = new ReportBack();
            reportBack.setCheckStatus("不通过");
            reportBack.setRejectAdvice(report.getRejectAdvice());
            reportBack.setRejectFile(report.getRejectFile());
            reportBack.setReportSavePath(report.getReportSavePath());
            reportBack.setRejectRealFile(report.getRejectRealFile());
            reportBack.setAuditTime(report.getAuditTime());
            reportBack.setAuditUserName(report.getAuditUserName());
            reportBack.setReportId(reportId);
            return reportBack;
        }
        return new ReportBack();
    }
}
